﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CarbonExchange.Bll;
using System.Web.Security;

public partial class UserControls_Login : UserControlBase
{
    protected override void OnInit(EventArgs e)
    {
        btnLogin.Click += new EventHandler(btnLogin_Click);
        base.OnInit(e);
    }

    void btnLogin_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            Acms.Bll.User user = Acms.Bll.User.GetByEmailAddress(txtEmailAddress.Text, CarbonExchangePage.AcmsContext.SiteId);
            if (user != null && user.AuthenticatePassword(txtPassword.Text))
            {
                //ToDo:If email not approved the do redirect here
                if (!user.EmailAuthenticated)
                {
                    CarbonExchangePage.AcmsContext.RedirectToUrl(string.Format("~/Profile/AuthenticateEmail.aspx?Email={0}", user.EmailAddress), CarbonExchangePage);
                }
                //Login
                CarbonExchange.Logger.ILogger logger = StructureMap.ObjectFactory.GetInstance<CarbonExchange.Logger.ILogger>();
                logger.Info(string.Format("Logging in '{0}'", user.EmailAddress));

                Guid key = user.GetLoginKey(false);
                HttpCookie authCookie = FormsAuthentication.GetAuthCookie(key.ToString(), false);

                FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
                
                //create new ticket to include the userdata field
                FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, key.ToString());

                authCookie.Value = FormsAuthentication.Encrypt(newTicket);
                Page.Response.Cookies.Add(authCookie);
                if (Request.QueryString["ReturnURL"] != null)
                {
                    Page.Response.Redirect(Page.ResolveUrl(Request.QueryString["ReturnURL"]), true);
                }
                else
                {
                    Page.Response.Redirect(CarbonExchangePage.AcmsContext.OriginalUrl, true);
                }
            }
            else
            {
                //invalid display message
                pnlLoginError.Visible = true;
            }
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
    }
}
